﻿using System.Windows.Controls;
using System.Windows;

namespace Xcj.Mes.WholeLine.ZH.HG.Shell.Common
{
    public class DataGridBehavior
    {
        public static readonly DependencyProperty RowNumbersProperty = DependencyProperty.RegisterAttached("RowNumbers", typeof(bool), typeof(DataGridBehavior), new FrameworkPropertyMetadata(false, OnRowNumbersChanged));

        private static void OnRowNumbersChanged(DependencyObject source, DependencyPropertyChangedEventArgs args)
        {
            DataGrid Grid = source as DataGrid;
            if (Grid == null) return;

            if ((bool)args.NewValue)
            {
                Grid.LoadingRow   += OnGridLoadingRow;
                Grid.UnloadingRow += OnGridUnloadingRow;
            }
            else
            {
                Grid.LoadingRow   -= OnGridLoadingRow;
                Grid.UnloadingRow -= OnGridUnloadingRow;
            }
        }

        private static void RefreshDataGridRowNumbers(object sender)
        {
            DataGrid Grid = sender as DataGrid;
            if (Grid == null) return;

            foreach (var item in Grid.Items)
            {
                var Row = (DataGridRow)Grid.ItemContainerGenerator.ContainerFromItem(item);
                if (Row != null) Row.Header = Row.GetIndex() + 1;
            }
        }

        private static void OnGridUnloadingRow(object sender, DataGridRowEventArgs e)
        {
            RefreshDataGridRowNumbers(sender);
        }

        private static void OnGridLoadingRow(object sender, DataGridRowEventArgs e)
        {
            RefreshDataGridRowNumbers(sender);
        }

        [AttachedPropertyBrowsableForType(typeof(DataGrid))]
        public static void SetRowNumbers(DependencyObject element, bool value)
        {
            element.SetValue(RowNumbersProperty, value);
        }

        public static bool GetRowNumbers(DependencyObject element)
        {
            return (bool)element.GetValue(RowNumbersProperty);
        }
    }
}
